<template>
  <div class="container">
    <el-card class="box-card">
      <div
        slot="header"
        class="clearfix"
      >
        <div class="change">
          <span v-if="$route.query.id">试题修改</span>
          <span v-else>试题录入</span>
        </div>
      </div>
      <el-form
        ref="form"
        :model="pubForm"
        :rules="rules"
        label-width="100px"
      >
        <!-- 学科： -->
        <el-form-item
          label="学科："
          prop="subjectID"
        >
          <el-select
            placeholder="请选择"
            style="width: 400px"
            v-model="pubForm.subjectID"
            @change="cataList"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in subjectList"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录： -->
        <el-form-item
          label="目录："
          prop="catalogID"
        >
          <el-select
            placeholder="请选择"
            style="width: 400px"
            v-model="pubForm.catalogID"
          >
            <el-option
              :label="item.label"
              :value="Number(item.value)"
              v-for="item in catalogList"
              :key="Number(item.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item
          label="企业："
          prop="enterpriseID"
        >
          <el-select
            placeholder="请选择"
            style="width: 400px"
            v-model="pubForm.enterpriseID"
          >
            <el-option
              :label="item.company"
              :value="item.id"
              v-for="item in companyList"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市： -->
        <el-form-item
          label="城市："
          prop="city"
        >
          <el-row>
            <el-select
              filterable
              placeholder="请选择"
              style="width: 198px; margin-right: 5px"
              v-model="pubForm.province"
              @change="getCity"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="item in provinceList"
                :key="item"
              ></el-option>
            </el-select>
            <el-select
              placeholder="请选择"
              style="width: 197px"
              v-model="pubForm.city"
              :filterable="filterable"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="item in cityList"
                :key="item"
              ></el-option>
            </el-select>
          </el-row>
        </el-form-item>
        <!-- 方向： -->
        <el-form-item
          label="方向："
          prop="direction"
        >
          <el-select
            placeholder="请选择"
            style="width: 400px"
            v-model="pubForm.direction"
          >
            <el-option
              :label="item"
              :value="item"
              v-for="item in directionList"
              :key="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型： -->
        <el-form-item
          prop="questionType"
          label="题型："
        >
          <el-radio-group v-model="pubForm.questionType">
            <el-radio
              v-for="(item, index) in quesTypes"
              :key="item"
              :label="`${index + 1}`"
            >{{
              item
            }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          prop="difficulty"
          label="难度："
        >
          <el-radio-group v-model="pubForm.difficulty">
            <el-radio
              v-for="(item, index) in difficulties"
              :key="item"
              :label="`${index + 1}`"
            >{{
              item
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干：
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)"
        -->
        <el-form-item
          label="题干："
          prop="question"
        >
          <quill-editor
            v-model="pubForm.question"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <!-- 选项： -->
        <!-- 单选多选列表数据项 -->
        <el-form-item
          v-if="pubForm.questionType === '1'"
          label="选项："
        >
          <el-radio-group v-model="radioValue">
            <el-radio
              v-for="item in pubForm.options"
              :key="item.code"
              :label="item.code"
              style="display: block; padding-top: 10px; margin-left: 10px"
            >
              <span>{{ item.code }}：</span>
              <el-input
                v-model="item.title"
                style="margin-right: 5px; width: 250px"
              />
              <div class="avatar">
                <UploadImage v-model="item.img"></UploadImage>
              </div>
            </el-radio>
            <el-button
              :disabled="+pubForm.questionType !== 2"
              type="danger"
              size="small"
              @click="addoption"
            >+增加选项与答案</el-button>
          </el-radio-group>

        </el-form-item>

        <el-form-item
          v-else-if="pubForm.questionType === '2'"
          label="选项："
        >
          <el-checkbox-group v-model="checkList">
            <el-checkbox
              v-for="item in pubForm.options"
              :key="item.code"
              :label="item.code"
              style="display: block; padding-top: 10px; margin-left: 10px"
            >
              <span>{{ item.code }}：</span>
              <el-input
                v-model="item.title"
                style="margin-right: 5px; width: 250px"
              />
              <div class="avatar">
                <UploadImage v-model="item.img"></UploadImage>
              </div>
            </el-checkbox>
          </el-checkbox-group>
          <el-button
            :disabled="+pubForm.questionType !== 2"
            type="danger"
            size="small"
            @click="addoption"
          >+增加选项与答案</el-button>
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频：">
          <el-input
            style="width: 400px"
            v-model="pubForm.videoURL"
          ></el-input>
        </el-form-item>
        <!-- 答案解析 -->
        <el-form-item
          label="答案解析："
          prop="answer"
        >
          <quill-editor
            v-model="pubForm.answer"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <!-- 题目备注、 -->
        <el-form-item label="题目备注：">
          <el-input
            type="textarea"
            :rows="2"
            v-model="pubForm.remarks"
            class="textarea"
          >
          </el-input>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签：">
          <!-- multiple:是否多选
    filterable：是否可搜索
    allow-create：是否允许用户创建新条目，需配合 filterable 使用
    default-first-option：在输入框按下回车，选择第一个匹配项 -->
          <el-select
            v-model="pubForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择试题标签"
            class="textarea"
          >
            <el-option
              v-for="item in tagList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button v-if="$route.query.id" type="success" @click="onSubmit">确认修改</el-button>
          <el-button
          v-else
            type="primary"
            @click="onSubmit"
          >确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// import { addQuillTitle } from '@/utils/quill-till.js'
import UploadImage from '@/components/UploadImg/index'
import { simple as simpleSubject } from '@/api/hmmm/subjects.js'
import { simple as catalogListAPI } from '@/api/hmmm/directorys.js'
import { simple as tagListAPI } from '@/api/hmmm/tags.js'
import { list as companyListAPI } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction } from '@/api/hmmm/constants.js'
import { add, detail, update } from '@/api/hmmm/questions.js'
export default {
  components: {
    quillEditor,
    UploadImage
  },
  created () {
    // 获取学科列表
    this.getSubjectList()
    // 获取企业列表
    this.getCompanyList()
    // 获取城市列表
    this.getProvinceList()
    // 获取方向列表
    this.directionList = direction
  },
  // mounted () {
  //   addQuillTitle()
  // },
  data () {
    return {
      pubForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { code: 'A', title: '', img: '', isRight: 0 },
          { code: 'B', title: '', img: '', isRight: 0 },
          { code: 'C', title: '', img: '', isRight: 0 },
          { code: 'D', title: '', img: '', isRight: 0 }
        ], // 选项(对象数组)code, title, img, isRight
        videoURL: '', // 解析视频地址
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'change' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'change' }]
      },
      // 添加文章的表单验证规则
      pubFormRules: {
        title: [
          { required: true, message: '标题必填', trigger: 'blur' },
          { min: 1, max: 30, message: '标题长度1~30位', trigger: ['blur', 'change'] }
        ],
        cate_id: [{ required: true, message: '请选择一个分类', trigger: 'blur' }]
      },
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote'], // 引用

            ['code-block', 'image', 'link'] // 代码块、链接、图片
          ]
        },
        placeholder: ''
      },
      quesTypes: ['单选', '多选', '简答'],
      // 试题难度
      difficulties: ['简单', '一般', '困难'],
      imageUrl: '',
      // optionLength: 4, // 有多少个选项
      // // options: [], // 选项(A,B,C)
      // isRight: '', // 单选选中的索引
      // checkList: [], // 复选 选中索引的集合
      // radioChoiceList: [], // 点击多选时 保存单选的数据
      // multiChoiceList: [], // 点击单选时 保存多选的数据
      // multiOptionLength: '', // 点击单选时 保存多选的选项数
      isID: false, // 判断是否为修改
      subjectList: [], // 学科列表
      catalogList: [], // 目录列表
      companyList: [], // 企业列表
      provinceList: [], // 城市列表
      cityList: [], // 省份列表
      directionList: [], // 方向列表
      // 试题标签
      tagList: [],
      // 单选多选列表数据项
      checkList: [], // 多选被选中的code
      radioValue: 0, // 单选被选中的code
      filterable: false
      // catalogLists: []
    }
  },
  // 侦听器，用来侦听路由的变化
  watch: {
    // 当前路由对象的路径
    '$route.path': {
      handler () {
        if (this.$route.query.id) {
          this.updateList(this.$route.query.id)
        }
      },
      immediate: true
    }
  },
  methods: {
    // 上传图片
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // // 添加复选框
    addoption () {
      // String.fromCharCode：
      const code = String.fromCharCode('A'.charCodeAt(0) + this.pubForm.options.length)
      this.pubForm.options.push({ code: code, title: '', img: '', isRight: 0 })
    },
    // // 判断假数据中的ABCD是否存在真数据里面
    // getIsTrue () {
    //   this.option.forEach(item => {
    //     item.isRight = this.pubForm.options.code.includes(item.code)
    //   })
    // 获取学科列表
    async getSubjectList () {
      const res = await simpleSubject()
      this.subjectList = res.data

      // console.log(this.subjectList)
      // console.log(this.subjectList)
    },
    // 选中学科，就获取目录
    async cataList () {
      this.pubForm.catalogID = ''
      this.pubForm.tags = ''
      // 获取目录列表
      const res = await catalogListAPI({ subjectID: this.pubForm.subjectID })
      // this.catalogList = res.data
      // res.data.map(item => { item.id = Number(item.id) })
      this.catalogList = res.data

      // 获取试题标签列表
      const resTag = await tagListAPI({ subjectID: this.pubForm.subjectID })
      this.tagList = resTag.data
    },
    // 数据回显的时候，选择学科的时候，对应的目录中文显示
    async catelog () {
      // 获取目录列表
      const res = await catalogListAPI({ subjectID: this.pubForm.subjectID })
      this.catalogList = res.data
    },
    // 获取企业列表
    async getCompanyList () {
      const res = await companyListAPI()
      this.companyList = res.data.items
    },
    // 获取城市列表
    getProvinceList () {
      this.provinceList = provinces()
      // console.log(this.provinceList)
    },
    // 选中城市后，自定触发函数，获取地区
    getCity (val) {
      this.cityList = citys(val)
      delete this.pubForm.city
      this.filterable = true
    },
    // 重置表单
    resetForm () {
      this.$refs.form.resetFields()
      this.radioValue = 0
      this.checkList = []
      this.pubForm.videoURL = ''
      this.pubForm.tags = []
      this.pubForm.remarks = ''
      delete this.pubForm.city
      this.filterable = false
    },
    // 确认提交按钮
    onSubmit () {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // 处理选项,如果这个题型为1，选项就为单选
        if (+this.pubForm.questionType === 1) {
          // 单选
          // 如果是单选，就遍历options这个选项，如果被选中的code和假数据中的code一样，就将按钮的状态转为true
          this.pubForm.options.forEach(item => {
            if (item.code === this.radioValue) {
              item.isRight = 1
            }
          })
          // 如果题型是多选
        } else if (+this.pubForm.questionType === 2) {
          // 多选
          // 就遍历被选中多选按钮的code，在options这个假数据中如果能找到多选框被选中的code，就将它的状态改为1(也就是被选中)
          this.checkList.forEach(code => {
            const item = this.pubForm.options.find(item => item.code === code)
            if (item) item.isRight = 1
          })
        } else {
          // 否则就是简答，就将options赋值为空
          this.pubForm.options = []
        }
        if (this.pubForm.id) {
          // 编辑
          await update(this.pubForm)
          this.$message.success('更新成功')
        } else {
          // 添加
          await add(this.pubForm)
          this.$message.success('添加成功')
        }
        this.resetForm()
        this.$router.push('/questions/list')
      })
    },
    // 点击修改，回显数据
    async updateList (id) {
      const { data } = await detail({ id: id })
      const options = data.options
      // 将接收到的code从小到大排序
      options.sort((a, b) => a.code.charCodeAt() - b.code.charCodeAt())
      if (data.questionType === '1') {
        // 如果返回数据的题干类型为单选，就将服务器返回的被选中的code给单选按钮绑定的radioValue实现数据的双向绑定
        this.radioValue = options.find(item => item.isRight === 1).code
        // 如果数返回数据的题干类型为多选
      } else if (data.questionType === '2') {
        // 则遍历返回的options数组，将isRight为1的code push到checkList中去，这样的话多选框就可以实现双向绑定
        options.forEach(item => {
          if (item.isRight === 1) {
            this.checkList.push(item.code)
          }
        })
      }
      this.pubForm = data
      // 解决回显的时候将目录的中文回显出来
      this.catelog()
      this.pubForm.tags = data.tags.split(',')
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  padding: 20px;
}
// 富文本编辑器的高度（当前组件的样式，加入了 scoped，则不会影响子组件的样式。）
// 需要使用样式穿透
::v-deep .ql-editor {
  min-height: 201px;
}
// 修改富文本的标题宽度
::v-deep .ql-toolbar.ql-snow {
  padding: 0;
}
.textarea {
  width: 400px;
  // height: 200px;
}
::v-deep.el-upload {
  .el-progress {
    position: absolute;
    top: 40%;
    width: 60px;
    height: 60px;

    .el-progress-circle {
      width: 100% !important;
      height: 100% !important;
    }
  }
}
.avatar {
  display: inline-block;
  position: relative;
  width: 100px;
  height: 60px;
  margin-left: 5px;

  .el-upload--picture-card {
    position: relative;
    width: 100px;
    height: 60px;

    span {
      position: absolute;
      top: -80%;
      left: 20%;
      // transform: translate(-50%,-50%);
    }
  }

  .el-progress {
    position: absolute;
    top: 40%;
    width: 60px;
    height: 60px;

    .el-progress-circle {
      width: 100% !important;
      height: 100% !important;
    }
  }

  .el-upload-list__item {
    width: 100px;
    height: 60px;
  }
}
.avatar {
  display: inline-block;
  position: relative;
  width: 100px;
  height: 60px;
  margin-left: 5px;

  .el-upload--picture-card {
    position: relative;
    width: 100px;
    height: 60px;

    span {
      position: absolute;
      top: -80%;
      left: 20%;
      // transform: translate(-50%,-50%);
    }
  }

  .el-progress {
    position: absolute;
    top: 40%;
    width: 60px;
    height: 60px;

    .el-progress-circle {
      width: 100% !important;
      height: 100% !important;
    }
  }

  .el-upload-list__item {
    width: 100px;
    height: 60px;
  }

  .display {
    width: 100px;
    height: 60px;
  }
}
</style>
